package com.qtu.user_service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qtu.entity.BmMember;
import com.qtu.user_service.feign.SellerFeignService;
import com.qtu.user_service.mapper.SellerMapper;
import com.qtu.user_service.service.SellerService;
import com.qtu.util.BCryptUtil;
import com.qtu.util.CacheUtil;
import com.qtu.util.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class SellerServiceImpl extends ServiceImpl<SellerMapper, BmMember> implements SellerService {

    @Autowired
    private SellerMapper sellerMapper;

    @Autowired
    private SellerFeignService sellerFeignService;

    /**
     *  商铺登录
     */
    @Override
    public Map<String, Object> BmMemberLogin(String tel, String password, HttpServletRequest request, HttpServletResponse response) {
        Map<String,Object> map = new HashMap<>();
        if(tel == null || tel.isEmpty()){//不判断报：NullPointerException
            map.put("resultMessage","手机号不能为空!");
            return map;
        }
        BmMember member = sellerMapper.selectOne(new QueryWrapper<BmMember>().eq("tel", tel));
        if(member == null || member.getIsDeleted() == 1){
            map.put("resultMessage","该商铺不存在!");
            return map;
        }
        if(false == BCryptUtil.matches(password,member.getPassword())){
            map.put("resultMessage","密码错误!");
            return map;
        }
        //1、商铺登录成功，把用户信息写入redis，生成一个用户token
        String token = UUID.randomUUID().toString().replace("-","").toLowerCase();

        //2、存入Redis，并设置过期时间（注意：token、userInfo存储结构为 Map）
        String set = sellerFeignService.setByTime(token, member, 60);//time：分钟
        if(!StringUtils.equals(set,"ok")){
            map.put("resultMessage","登录授权失败,请稍后再试!");
            return map;//预防 openfeign服务调用失败 or 缓存雪崩
        }

        //4、响应前端
        map.put("resultMessage","ok");
        map.put("token",token);
        map.put("member",member);
        return map;
    }

    /**
     * 注册
     * @param bmMember
     * @return
     */
    @Transactional
    @Override
    public Map<String, String> register(BmMember bmMember) {
        Map<String, String> map = new HashMap<>();
        int row = 0;
        BmMember m=sellerMapper.selectOne(new QueryWrapper<BmMember>().eq("tel", bmMember.getTel()));
        if (m == null){
            bmMember.setPassword(BCryptUtil.encode(bmMember.getPassword()));//1、密码加密
            row = sellerMapper.insert(bmMember);
            map.put("resultCode",String.valueOf(row));//2、注册成功
            return map;
        }
        map.put("resultCode",String.valueOf(row));
        map.put("resultMessage","您已注册，请登录！");
        return map;
    }

    /**
     * 修改密码
     * @param oldPassword
     * @param newPassword
     * @param token
     * @param id
     * @return
     */
    @Transactional
    @Override
    public Map<String,String> updatePassword(String oldPassword,String newPassword, String token, int id) {
        Map<String, String> map = new HashMap<>();
        int row = 0;
        Object obj = sellerFeignService.get(token);
        if(obj == null){
            map.put("resultCode",String.valueOf(row));
            map.put("resultMessage","登录失效，请重新登录！");
            return map;
        }
        BmMember member = (BmMember) CacheUtil.linkedHashMapToObject(obj, BmMember.class);
        boolean matches = BCryptUtil.matches(oldPassword, member.getPassword());
        if(matches){
            member.setPassword(BCryptUtil.encode(newPassword));
            row = sellerMapper.updateById(member);
            sellerFeignService.setByTime(token,member,60);
            map.put("resultCode",String.valueOf(row));
            map.put("resultMessage","修改成功！");
            return map;
        }
        map.put("resultCode",String.valueOf(row));
        map.put("resultMessage","原密码输入有误！");
        return map;
    }

    @Override
    public void loginOut(String token) {
        if(token == null) return;
        String exists = sellerFeignService.exists(token);
        if(StringUtils.equals("true",exists)){
            sellerFeignService.delete(token);
        }
    }
}
